<template>
  <!-- 包裹根标签，让transition功能生效 -->
  <div>
    <el-card shadow="never">
      <el-form inline>
        <el-form-item label="用户名">
          <el-input
            placeholder="请输入用户名"
            v-model="userFormData.username"
          ></el-input>
        </el-form-item>
        <el-form-item class="fr">
          <el-button type="primary" :icon="Search" @click="search">
            搜索
          </el-button>
          <el-button :icon="Refresh" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" class="m-t-15">
      <div class="flex-between">
        <div>
          <!-- 注意：@click="showDrawer" 这样写默认会有event参数 -->
          <el-button type="primary" :icon="Plus" @click="showDrawer()">
            添加
          </el-button>
          <el-button
            type="danger"
            :icon="Delete"
            :disabled="!selectRows.length"
            @click="batchRemove"
          >
            批量删除
          </el-button>
        </div>
        <el-space>
          <el-icon :size="18">
            <Refresh />
          </el-icon>
          <el-icon :size="18">
            <Setting />
          </el-icon>
        </el-space>
      </div>

      <el-table
        :data="list"
        class="m-t-15"
        border
        row-key="id"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          label="#"
          type="index"
          align="center"
        ></el-table-column>
        <el-table-column label="id" prop="id" align="center"></el-table-column>
        <el-table-column
          label="用户名"
          prop="username"
          align="center"
        ></el-table-column>
        <el-table-column
          label="用户昵称"
          prop="name"
          align="center"
        ></el-table-column>
        <el-table-column
          label="角色列表"
          prop="roleName"
          align="center"
        ></el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          sortable
          sort-by="createTime"
        >
          <template v-slot="{ row }">
            <el-tooltip :content="row.createTime" placement="top">
              <span class="els">{{ row.createTime }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <!-- 
          sortable 开启排序
          sort-by="updateTime" 按照数据哪个属性进行排序
        -->
        <el-table-column
          label="更新时间"
          align="center"
          sortable
          sort-by="updateTime"
        >
          <template v-slot="{ row }">
            <el-tooltip :content="row.updateTime" placement="top">
              <span class="els">{{ row.updateTime }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center">
          <!-- 不支持直接写template，要么不写，要么写上内容 -->
          <template v-slot="{ row }">
            <el-button
              type="primary"
              link
              :icon="User"
              @click="showAssignRoleDrawer(row)"
            >
              分配角色
            </el-button>
            <el-button
              type="primary"
              link
              :icon="Edit"
              @click="showDrawer(row)"
            >
              编辑
            </el-button>
            <el-button type="primary" link :icon="Delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 
        v-model:current-page 当前页码
        v-model:page-size 每页条数
        page-sizes 每页条数选项
      -->
      <!-- <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="m-t-15 flex-end"
      /> -->

      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="m-t-15 flex-end"
      />
    </el-card>

    <!-- 添加或更新用户 -->
    <Drawer ref="drawerRef" @success="getList" />
    <!-- 给用户分配角色 -->
    <AssignRoleDrawer ref="assignRoleDrawerRef" @success="getList" />
  </div>
</template>

<script lang="ts" setup name="User">
import {
  Search,
  Refresh,
  Plus,
  Delete,
  Setting,
  Edit,
  User,
} from '@element-plus/icons-vue'
import { ref, onMounted, watch, reactive } from 'vue'
import { getUserList } from '@/api'
import type { User as UserType } from '@/api/acl/types'
import { ElMessageBox, ElMessage } from 'element-plus'

import Drawer from './components/Drawer.vue'
import AssignRoleDrawer from './components/AssignRoleDrawer.vue'
import { batchRemoveUserList } from '@/api/acl/user'

/*********************** 1. 获取用户分页列表数据 ***********************/
const currentPage = ref(1) // 当前页码
const pageSize = ref(5) // 每页条数
const list = ref<UserType.UserList>([]) // 用户列表数据
const total = ref(0) // 总数
const loading = ref(false) // loading

// 获取用户列表
const getList = async () => {
  loading.value = true
  const res = await getUserList(
    currentPage.value,
    pageSize.value,
    userFormData.username,
  )
  list.value = res.data.records
  total.value = res.data.total
  loading.value = false
}
// 挂载完成，发送请求获取数据
// onMounted(() => {
//   getList()
// })
onMounted(getList)

// 官方不推荐使用 @size-change="handleSizeChange" 和 @current-change="handleCurrentChange"
// 所以使用 v-model 更新数据，watch 监视 数据变化，发送请求
watch([pageSize, currentPage], getList)

// 点击分页触发函数
// const handleSizeChange = (newPageSize: number) => {
//   pageSize.value = newPageSize
//   getList()
// }
// const handleCurrentChange = (newCurrentPage: number) => {
//   currentPage.value = newCurrentPage
//   getList()
// }

/*********************** 2. 搜索重置功能 ***********************/

// 表单项数据一般用reactive定义
const userFormData = reactive({
  username: '',
})

// 搜索
const search = () => {
  // 问题：如果用户在第二页点击搜索，默认搜索第二页数据（可能没有）
  // 解决：将页面设置为1
  currentPage.value = 1
  pageSize.value = 5
  getList()
}

// 重置
const reset = () => {
  // 将搜索条件清空
  currentPage.value = 1
  pageSize.value = 5
  userFormData.username = ''
  getList()
}

/*********************** 3. 添加或修改用户功能 ***********************/
const drawerRef = ref()

const showDrawer = (row?: UserType.UserItem) => {
  drawerRef.value.open(row)
}

/*********************** 4. 分配用户角色功能 ***********************/
const assignRoleDrawerRef = ref()

const showAssignRoleDrawer = (row: UserType.UserItem) => {
  assignRoleDrawerRef.value.open(row)
}

/*********************** 5. 批量删除功能 ***********************/
const selectRows = ref<UserType.UserList>([])

const handleSelectionChange = (rows: UserType.UserList) => {
  selectRows.value = rows
}

const batchRemove = async () => {
  await ElMessageBox.confirm('您确认要删除选中的数据吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  await batchRemoveUserList(selectRows.value.map((user) => user.id))
  ElMessage.success('批量删除成功')
  getList()
}
</script>

<style scoped lang="scss">
/* scoped 让样式只对当前组件生效（子组件的根标签） */
.el-form-item {
  margin-bottom: 0;
}
</style>
